<!-- 核销员管理 -->
<template>
  <div class="the-list">
    <div class="panel-search">
      <el-form inline :model="table.query" class="demo-form-inline">
        <el-form-item label="账号">
          <el-input
            v-model="table.query.account"
            placeholder="账号"
            clearable
          />
        </el-form-item>

        <el-form-item label="姓名">
          <el-input v-model="table.query.name" placeholder="姓名" clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="tableFn.onSubmit">搜索</el-button>
          <el-button type="primary" @click="tableFn.onResetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="panel-table">
      <div class="table-head">
        <span>核销员列表</span>
        <div>
          <el-button type="primary" @click="addEditFn.openPanel('add')"
            >添加</el-button
          >
        </div>
      </div>
      <el-table
        :data="table.list"
        stripe
        :header-cell-style="{ backgroundColor: '#ededed', padding: '12px 0' }"
        style="width: 100%"
        border
      >
        <el-table-column prop="account" label="账号" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="logoUrl" label="默认头像">
          <template #default="{ row }">
            <div v-show="row && row.headImg"
                 style="display: inline-block"
                 @click="
                tableFn.openImageViewer(
                  [row.headImg],
                   0
                )
              "
            >
              <el-image
                  style="width: 120px; height: 120px; background-color: #f5f7fa"
                  :src="row.headImg"
                  fit="contain"
              ></el-image>
            </div>
            <p v-show="!row || !row.headImg">--</p>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <label :style="{ color: ['#F56C6C', '#67C23A'][row.status] }">{{
              row.status == "1" ? "正常" : "停用" || "--"
            }}</label>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="480px"
          align="center"
        >
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              plain
              @click="delFn.sureDelete(row)"
              >删除</el-button
            >
            <el-button
              type="primary"
              size="small"
              plain
              @click="addEditFn.openPanel('edit', row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="small"
              plain
              v-if="row.status == '1'"
              @click="stateFn.sureUpdate(row)"
              >{{ '停用' }}</el-button
            >
            <el-button
              type="primary"
              size="small"
              plain
              v-if="row.status == '0'"
              @click="stateFn.sureUpdate(row)"
              >{{ '启用' }}</el-button
            >
            <el-button
              type="primary"
              size="small"
              plain
              @click="tableFn.openEventList(row)"
              >活动列表</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination">
        <pagination
          :total="table.total"
          v-model:page="table.query.page"
          v-model:limit="table.query.pageSize"
          @pagination="tableFn.getTableList"
        />
      </div>
    </div>
    <el-dialog
      :title="addEditData.isEdit ? '修改核销员信息' : '新增核销员'"
      v-model="addEditData.showPanel"
      width="30%"
      center
    >
      <el-form inline :model="addEditData.post">
        <el-row>
          <el-form-item prop="account" label="账号" label-width="120px">
            <el-input
            style="width:360px"
              v-model="addEditData.post.account"
              placeholder="请输入手机号"
              clearable
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="name" label="姓名" label-width="120px">
            <el-input
            style="width:360px"
              v-model="addEditData.post.name"
              placeholder="请输入姓名"
              clearable
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="headImg" label="默认头像" label-width="120px">
            <upload-oss
                list-type="picture-card"
                :limit="1"
                :imageUrl="addEditData.headImg"
                :beforeUpload="(file)=>addEditFn.beforeUpload(file)"
                @upload="addEditFn.afterUpload">
            </upload-oss>
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addEditFn.closePanel()">取 消</el-button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <el-button type="primary" @click="addEditFn.submitData()"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script>
import { reactive, watch } from "vue";
import {
  getVerifierList,
  addVerifier,
  editVerifier,
  deleteVerifier,
} from "@/api/eventsinfo.js";
import { ElMessage, ElMessageBox } from "element-plus";
import Pagination from "@/components/Pagination";
import { onBeforeRouteUpdate, useRouter } from "vue-router";
import UploadOss from "@/components/AliOSS";
import imageViewer from "@/components/imageViewer/index2";

export default {
  name: "verifierManage",
  components: {UploadOss},
  setup() {
    const { $data: table, $fn: tableFn } = tableModule();
    const { $data: addEditData, $fn: addEditFn } = addOrEditModule(tableFn);
    const { $data: delData, $fn: delFn } = deleteModule(tableFn);
    const { $data: stateData, $fn: stateFn } = stateModule(tableFn);

    return {
      table,
      tableFn,
      addEditData,
      addEditFn,
      delData,
      delFn,
      stateData,
      stateFn,
    };
  },
};
// 列表功能模块
function tableModule() {
  const router = useRouter();
  const backup = {
    query: {
      pageSize: 10,
      page: 1,
      name: "",
      account: "",
      type: "0",
    },
  };
  const $data = reactive({
    query: { ...backup.query },
    list: [],
    total: 0,
  });

  const $fn = {
    getTableList() {
      getVerifierList($data.query).then((res) => {
        if (res.code === 0) {
          $data.list = res.data.items;
          $data.total = res.data.pagination.total_record;
        }
      });
    },
    openImageViewer(list, index) {
      imageViewer({ initialIndex: index, urlList: list });
    },
    onResetQuery() {
      $data.query = { ...backup.query };
      $fn.getTableList();
    },
    onSubmit() {
      $data.query.page = 1;
      $fn.getTableList();
    },
    openEventList(row) {
      router.push("/eventsInfo/verifierEventList/" + row.id);
    },
  };

  $fn.getTableList();

  return {
    $data,
    $fn,
  };
}

// 新增、编辑
function addOrEditModule(tableFn) {
  const $data = reactive({
    showPanel: false,
    isEdit: false,
    headImg: undefined,
    post: {
      id: "",
      account: "",
      name: "",
      headImg: ""
    }, //提交的数据
  });
  const $fn = {
    openPanel(operate, row) {
      if (operate === "add") {
        $data.post = {
          id: "",
          account: "",
          name: "",
          headImg: ""
        }; //提交的数据
        $data.isEdit = false;
      } else if (operate === "edit") {
        $data.isEdit = true;
        $data.post.id = row.id;
        $data.post.account = row.account;
        $data.post.name = row.name;
        $data.post.headImg = row.headImg;
        $data.headImg = [{url:row.headImg}]
      }
      $data.showPanel = true;
    },
    closePanel() {
      $data.showPanel = false;
      $data.headImg = undefined;
      $data.post = {
        id: "",
        account: "",
        name: "",
        headImg: ""
      }
    },
    closedPanel() {
      $data.post = {
        id: "",
        account: "",
        name: "",
      };
    },
    submitData() {
      console.log("req data:", $data.post);
      let { id, account, name,headImg } = $data.post;
      // 数据验证
      if (!account) {
        ElMessage.error("请填写账号！");
        return;
      }
      if (!name) {
        ElMessage.error("请填写名称！");
        return;
      }
      if (
        !/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/.test(
          account
        )
      ) {
        //默认添加"#"
        ElMessage.error("请输入一个正确的手机号作为账号！");
        return;
      }
      if(!headImg){
        headImg = "https://img.qumoyugo.com/img/2YRDV5ASYQOP0PI864BYZ1651137572615.png"
      }
      if ($data.isEdit) {
        let req = { id, account, name,headImg };
        editVerifier(req).then((res) => {
          if (res.code === 0) {
            ElMessage.success("修改成功！");
            tableFn.getTableList();
            $fn.closePanel();
          }
        });
      } else {
        let req = { account, name,headImg, type: 0 };
        addVerifier(req).then((res) => {
          if (res.code === 0) {
            ElMessage.success("添加成功！");
            tableFn.getTableList();
            $fn.closePanel();
          }
        });
      }
    },
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        const size = file.size / 1024;
        if (size > 1024) {
          ElMessage.error("图片大小不能超过 1 MB！");
          reject();
          return;
        }
        resolve();
      });
    },
    afterUpload(list) {
      const url = list[0];
      if (!url) {
        $data.post.headImg = "";
        $data.headImg = undefined;
        return;
      }
      $data.post.headImg = "https://img.qumoyugo.com" + url.showUrl;
      $data.headImg = [{url:"https://img.qumoyugo.com" + url.showUrl}]
    },
  };

  tableFn.openPanel = $fn.openPanel;
  return {
    $data,
    $fn,
  };
}

// 删除
function deleteModule(tableFn) {
  const $fn = {
    sureDelete(row) {
      ElMessageBox.confirm("是否确认删除该核销员？", "确认删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          $fn.deleteItem(row);
        })
        .catch(() => {});
    },
    deleteItem(row) {
      // 发起删除
      console.log("发起删除");
      deleteVerifier(row.id).then((res) => {
        if (res.code === 0) {
          ElMessage.success("删除成功！");
          tableFn.getTableList();
        }
      });
    },
  };
  return {
    $fn,
  };
}

// 修改状态
function stateModule(tableFn) {
  const $fn = {
    sureUpdate(row) {
      let text = row.status == '1' ? "停用" : "启用";
      ElMessageBox.confirm(`是否确认${text}该核销员？`, `确认${text}`, {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          $fn.updateItem(row);
        })
        .catch(() => {});
    },
    updateItem(row) {
      let text = row.status == "1" ? "停用" : "启用";
      let { id, status } = row;
      status = status == "1" ? "0" : "1";
      let req = { id, status };
      editVerifier(req).then((res) => {
        if (res.code === 0) {
          ElMessage.success(`${text}成功！`);
          tableFn.getTableList();
        }
      });
    },
  };
  return {
    $fn,
  };
}
</script>
<style scoped lang="scss">
@import "@/styles/tablePage.scss";
// .the-list {
//   height: 100%;
// }
.el-form-item {
  margin-bottom: 8px;
}
</style>
